const Service = require('egg').Service

class UserService extends Service{
  async find(uid){
    let sql = "select * from wy_user where uid = ?"
    let data = await this.app.mysql.query(sql,[uid])
    return data
  }

  async memory(page,type){
    let  pageNum = 15
    if(!page) page = 1
    let start = parseInt((page-1)*pageNum + 1)
    let sql = "select * from wy_laptop limit ? , ? "
    let sqlParams = []
    let sqlCount = "select count(*) from wy_laptop "
    let sqlCountParams = []
    if(type){
      let index = sql.indexOf('limit')
      sql = sql.slice(0,index) + " where family_id = ? " + sql.slice(index)
      sqlParams.push(type)
      sqlCount += " where family_id = ?"
      sqlCountParams.push(type)
    }
    let total = await this.app.mysql.query(sqlCount,sqlCountParams)//总数
    page = {
      total:total[0]['count(*)'],
      pageNum,
      currentPage:page
    }
    let data = await this.app.mysql.query(sql,sqlParams.concat([start,pageNum]))//分页
    return {page,res:data}
  }

  async saveGithubUser(data){
    let sql = "select count(*) from wy_user where email = ?"
    let count = await this.app.mysql.query(sql,[data.email])
    if(count[0]['count(*)'] > 0){
      return
    }
    sql = 'insert into wy_user (uid,uname,upwd, email,phone,avatar,user_name,gender) values (null,?,null,?,null,?,null,null)'
    await this.app.mysql.query(sql,[data.uname,data.email,data.avatar])
  }

  // 该方法会自动注入到ctx.service.user对象下
  /**
   * @param page
   * @param pageSize
   * @param type 
   */
  async getList(page,pageSize,type){
    let start = parseInt((page-1)*pageSize),condition = "",sqlParams = []
    let roles = ["NORMAL_USER","DQ_SINGER","DQ_OFFICIAL_ACCOUNT"]
    if(roles.indexOf(type) > -1){ // 如果是合法用户，拼接where条件语句
      condition = "where type = ?"
      sqlParams = [type]
    }
    let sql = `select * from user ${condition} limit ? , ? `
    let data = await this.app.mysql.query(sql,sqlParams.concat([start,pageSize]))//分页
    return data
  }
  async getInfo(id){
    const data = await this.app.mysql.get("user", { id });
    if(!data){
      throw new Error("用户信息不存在")
    }
    return data
  }
}
module.exports = UserService

/**
 * Dao层
 * JavaBean层
 * Servlet层
*/
